<template>
  <div
    id="file_excel"
    ref="excelRef"
    v-loading="isLoading"
    element-loading-text="加载中，请耐心等待..."
    :style="{ height: height + 'px' }"
  ></div>
</template>
<script>
import jsPreviewExcel from "@js-preview/excel";
import "@js-preview/excel/lib/index.css";
import { isBase64String, base64ToURL } from "@/utils/file_preview_format";

export default {
  name: "FileExcel",
  props: {
    src: {
      required: true,
    },
  },
  data() {
    return {
      height: 700,
      isLoading: false,
    };
  },
  mounted() {
    if (this.src) {
      this.previewExcel();
    }
    // 获取到 excel 可以占用的最大高度
    if (this.$refs.excelRef) {
      this.height = this.getElementHeight(this.$refs.excelRef) - 10;
    }
  },
  methods: {
    previewExcel() {
      this.isLoading = true;
      if (isBase64String(this.src)) {
        const blob = base64ToURL(
          this.src,
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        );
        this.viewFile(blob);
      } else {
        this.viewFile(this.src);
      }
    },
    viewFile(src) {
      const myExcelPreviewer = jsPreviewExcel.init(
        document.getElementById("file_excel"),
        { minColLength: 0, showContextmenu: true },
      );
      myExcelPreviewer
        .preview(src)
        .then(() => {
          this.$emit("succeed");
          this.isLoading = false;
        })
        .catch((e) => {
          this.$emit("error", e);
          this.isLoading = false;
        });
    },
    getElementHeight(el) {
      return document.documentElement.clientHeight - this.getElementTop(el);
    },
    getElementTop(el) {
      let actualTop = el.offsetTop;
      let current = el.offsetParent;
      while (current !== null) {
        actualTop += current.offsetTop;
        current = current.offsetParent;
      }
      return actualTop;
    },
  },
};
</script>
<style scoped lang="scss">
#file_excel {
}
</style>